package com.anlu.base.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerExample {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private int value = 0;
    private boolean isProduced = false;

    public void produce() throws InterruptedException {
        lock.lock();
        try {
            while (isProduced) {
                condition.await(); // 等待消费者消费
            }
            value++; // 生产数据
            System.out.println("Produced: " + value);
            isProduced = true;
            condition.signal(); // 唤醒一个消费者线程
        } finally {
            lock.unlock();
        }
    }

    public void consume() throws InterruptedException {
        lock.lock();
        try {
            while (!isProduced) {
                condition.await(); // 等待生产者生产
            }
            System.out.println("Consumed: " + value);
            isProduced = false;
            condition.signal(); // 唤醒一个生产者线程
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ProducerConsumerExample example = new ProducerConsumerExample();

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    example.produce();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    example.consume();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}